package puyu.manage.service.menu.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import puyu.manage.service.common.config.BaseController;
import puyu.manage.service.constant.AjaxResult;
import puyu.manage.service.menu.service.SysMenuServiceI;
import puyu.manage.service.utils.StringUtils;
import puyu.manage.service.utils.TreeUtil;
import puyu.manage.service.utils.except.CustomException;
import puyu.manage.service.utils.tree.Zone;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 *  @ClassName: 菜单信息管理
 *  @author: whl
 *  @Date: 2024/6/6 15:26
 *  @Description: Description of this class
 */
@RestController
@Api(tags = "菜单信息")
@RequestMapping("/system/menu")
public class SysMenuController extends BaseController {
    @Autowired(required = false)
    private SysMenuServiceI menuService;

    /**
     * 获取帆软菜单信息
     */
    @ApiOperation("获取帆软菜单信息")
    @GetMapping("/getFinereport")
    public AjaxResult getFinereport() {
        List<Map<String,Object>> menus = menuService.selectMenuList("");
        List<Map<String,Object>> collect = menus.stream()
                .filter(v -> StringUtils.isNotEmpty(v.get("path")+"") && (v.get("path")+"").endsWith("Ifr"))
                .collect(Collectors.toList());
        return AjaxResult.success(collect);
    }

    /**
     * 获取菜单列表
     */
    @ApiOperation("获取菜单列表树")
    @GetMapping
    public AjaxResult list() {
        List<Map<String,Object>> menus = menuService.selectMenuList("");
        menus = menus.stream().filter(v -> Objects.nonNull(v) && !v.get("menuId").equals(v.get("parentId"))).collect(Collectors.toList());
        Map<Object, List<Map>> zoneByParentIdMap = menus.stream().collect(Collectors.groupingBy(item->item.get("parentId")));
        menus.forEach(zone->zone.put("children",zoneByParentIdMap.get(zone.get("menuId"))));
        menus = menus.stream().filter(v -> "0".equals(v.get("parentId")) || StringUtils.isEmpty(v.get("parentId")+"")).collect(Collectors.toList());
        return AjaxResult.success(menus);
    }


    /**
     * 根据菜单编号获取详细信息
     */
    @ApiOperation("根据菜单编号获取详细信息")
    @GetMapping(value = "/{menuId}")
    public AjaxResult getInfo(@PathVariable String menuId) {
        return AjaxResult.success(menuService.selectMenuById(menuId));
    }

    /**
     * 加载对应用户菜单列表树
     */
    @ApiOperation("加载对应用户菜单列表树")
    @GetMapping("/userMenuTreeselect/{userId}")
    public AjaxResult userMenuTreeselect(@PathVariable String userId) {
        List<Zone> menus = menuService.selectMenuTreeByUserTree(userId);
        //JSONArray objects = new TreeUtil().toTreeSelect(JSONArray.parseArray(JSON.toJSONString(menus)), "icon", "menuId", "parentId", "menuName", "isDataScope","englishName");
        return AjaxResult.success(menus);
    }

    /**
     * 加载对应角色菜单列表树
     */
    @ApiOperation("加载对应角色菜单列表树")
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public AjaxResult roleMenuTreeselect(@PathVariable("roleId") String roleId) {
        return AjaxResult.success(menuService.selectMenuListByRoleId(roleId));
    }

    /**
     * 新增菜单
     */
    @ApiOperation("新增菜单")
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@Validated @RequestBody Map<String,Object> menu) {
        if ("0".equals(menuService.checkMenuNameUniqueAdd(menu))) {
            throw new CustomException("A0202", menu.get("menuName"));
        }
        return toAjax(menuService.insertMenu(menu));
    }

    /**
     * 修改菜单
     */
    @ApiOperation("修改菜单")
    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult update(@Validated @RequestBody Map<String,Object> menu) {
        if ("0".equals(menuService.checkMenuNameUnique(menu))) {
            throw new CustomException("A0203", menu.get("menuName"));
        }
        return toAjax(menuService.updateMenu(menu));
    }

    /**
     * 删除菜单
     */
    @ApiOperation("删除菜单")
    @DeleteMapping("/{menuId}")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult delete(@PathVariable("menuId") String menuId) {
        if (menuService.hasChildByMenuId(menuId)) {
            throw new CustomException("A0204");
        }
        if (menuService.checkMenuExistRole(menuId)) {
            throw new CustomException("A0205");
        }
        return toAjax(menuService.deleteMenuById(menuId));
    }

}
